package com.tgl.vegetables.plug.dingdong;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.NonNull;

import com.tgl.vegetables.plug.service.BaseAccessibilityService;

import java.util.ArrayList;
import java.util.List;

public class DingDongAccessibilityService extends BaseAccessibilityService {

    private static final String TAG = "DingDongAccessibilityService";

    private int mSubmitClickCount = 0;

    public DingDongAccessibilityService() {
        super();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityService context, AccessibilityEvent accessibilityEvent) {
        Log.e(TAG, "accessibilityEvent = " + accessibilityEvent.toString());
        super.onAccessibilityEvent(context, accessibilityEvent);
        int type = accessibilityEvent.getEventType();
        String className = accessibilityEvent.getClassName().toString();
        if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            switch (className) {
                case "com.yaya.zone.home.HomeActivity":
                    mShopCarSelected = false;
                    processHomeActivity(accessibilityEvent);
                    break;
                case "cn.me.android.cart.activity.WriteOrderActivity":
                    processOrderActivity(accessibilityEvent);
                    break;
                default:
                    if (!accessibilityEvent.getText().isEmpty() && "选择送达时间".equals(accessibilityEvent.getText().get(0))) {
                        processTimeSelectView(accessibilityEvent);
                    }
                    break;
            }
        }
    }

    private void processHomeActivity(AccessibilityEvent accessibilityEvent) {
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        if (!mShopCarSelected) {
            mShopCarSelected = doSelectShopCar(accessibilityEvent.getSource());
        }
        mCurrentWindow = WINDOW_HOME;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private void processOrderActivity(AccessibilityEvent accessibilityEvent) {
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        mCurrentWindow = WINDOW_ORDER;
        mSubmitClickCount = 0;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private void processTimeSelectView(AccessibilityEvent accessibilityEvent) {
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mCurrentWindow = WINDOW_SELECT_TIME;
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        onClickTimeSelect();
        mCurrentWindow = WINDOW_ORDER;
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private boolean doSelectShopCar(AccessibilityNodeInfo nodeInfo) {
        nodeInfo = findAccessibilityNodeInfo(nodeInfo, "购物车", 0);
        if (nodeInfo != null) {
            performClick(nodeInfo, 2);
            return nodeInfo.isSelected();
        }
        return false;
    }

    @Override
    public void onInterrupt() {

    }

    private void onClickCalc() {
        if (!mShopCarSelected) {
            mShopCarSelected = doSelectShopCar(mAccessibilityService.getRootInActiveWindow());
        }
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfoViewId(mAccessibilityService.getRootInActiveWindow(), "com.yaya.zone:id/btn_submit", 0);
        if (nodeInfo != null) {
            performClick(nodeInfo, 0);
        }
    }

    private void onClickOrder() {
        AccessibilityNodeInfo root = mAccessibilityService.getRootInActiveWindow();
        if (root == null) {
            root = mRootAccessibilityNodeInfo;
        }
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "重新加载", 0);
        if (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                performClick(nodeInfo, 0);
            } else {
                performClick(nodeInfo, 1);
            }
            mSubmitClickCount = 0;
            return;
        }
        nodeInfo = findAccessibilityNodeInfo(root, "正在加载", 0);
        if (nodeInfo != null) {
            return;
        }

        nodeInfo = findAccessibilityNodeInfo(root, "立即支付", 0);
        if (nodeInfo != null) {
            if (mSubmitClickCount > 30) {
                mAccessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
            } else {
                performClick(nodeInfo, 0);
                mSubmitClickCount++;
            }
        }
    }

    private void onClickTimeSelect() {
        AccessibilityNodeInfo root = mRootAccessibilityNodeInfo;
        if (root == null) {
            root = mAccessibilityService.getRootInActiveWindow();
        }

        List<String> times = new ArrayList<>();
        times.add("06:30-14:30");
        times.add("14:30-22:30");
        boolean canNotOrder = false;
        boolean noFoundTime = true;
        for (String time : times) {
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, time, 0);
            if (nodeInfo != null) {
                noFoundTime = false;
                AccessibilityNodeInfo parent = nodeInfo.getParent();
                int childCount = parent.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    AccessibilityNodeInfo child = parent.getChild(i);
                    if (child.getText() != null && "已约满".equals(child.getText())) {
                        canNotOrder = true;
                        break;
                    }
                    Log.e(TAG, parent.getChild(i).getText().toString());
                }
                if (!canNotOrder) {
                    Rect rect = new Rect();
                    parent.getBoundsInScreen(rect);
                    autoClickPoint(rect.left + 10, rect.top + 10);
                    break;
                }
            }
        }

        if (noFoundTime) {
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "选择送达时间", 0);
            if (nodeInfo != null) {
                Rect rect = new Rect();
                nodeInfo.getBoundsInScreen(rect);
                autoClickPoint(540, rect.bottom + 20);
            }
        }

        final AccessibilityNodeInfo finalRoot = root;
        mHandler.postDelayed(() -> {
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfoViewId(finalRoot, "com.yaya.zone:id/iv_dialog_select_time_close", 0);
            if (nodeInfo != null) {
                performClick(nodeInfo, 0);
            }
        }, 20);
    }

    private void onClick() {
        switch (mCurrentWindow) {
            case WINDOW_HOME:
                onClickCalc();
                break;
            case WINDOW_ORDER:
                onClickOrder();
                break;
            default:
                break;
        }
    }

    @Override
    protected long getDuration() {
        return 100;
    }

    @Override
    public boolean handleMessage(@NonNull Message message) {
        switch (message.what) {
            case MSG_CLICK_EVENT:
                onClick();
                mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
                break;
            default:
                break;
        }
        return false;
    }
}
